﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
using AcctrueWMS.Foundation.Data;
using System.Web;
using System.Data;
using Newtonsoft.Json;

namespace AcctrueWMS.Foundation.Web
{
    /// <summary>
    /// 该类实现JSON串的解析,解析后,生成DataModel
    /// </summary>
    public class JsonTableConverter
    {
        /// <summary>
        /// 已实现主从表解析
        /// </summary>
        /// <param name="jsonStr"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        public static JObject ProcessToJsonObject(string jsonStr, DataModel model)
        {
            JObject obj = null;
            if (jsonStr != "undefined" || jsonStr.Length > 0)
            {
                jsonStr = HttpUtility.UrlDecode(jsonStr);
                StringBuilder sb = new StringBuilder("{");
                string[] kevArray = jsonStr.Split('&');
                ///首先将数据拆分成主表和明细表两个表,主表直接构造数据即可;明细表要获取明细表的行数,并构造相应数量的明细表的行
                Dictionary<string, List<string>> modelList = new Dictionary<string, List<string>>();
                modelList.Add(model.Name, new List<string>());
                for (int i = 0; i < model.Childs.Count; i++)
                {
                    modelList.Add(model.Childs[i].Name, new List<string>());
                }
                for (int i = 0; i < model.Brothers.Count; i++)
                {
                    modelList.Add(model.Brothers[i].Name, new List<string>());
                }
                #region 区分主表和细表
                foreach (string kev in kevArray)
                {
                    //decodekev的格式为ModelName+columnName+RowIndex
                  //  string decodekev = HttpUtility.UrlDecode(kev);
                    string decodekev = kev;
                    foreach (KeyValuePair<string, List<string>> modelInfo in modelList)
                    {
                        if (decodekev.Split('$')[0].Equals(modelInfo.Key))
                        {
                            modelInfo.Value.Add(decodekev);
                        }
                    }
                }
                #endregion
                foreach (KeyValuePair<string, List<string>> modelInfo in modelList)
                {
                    ///如果是主表,则构造主表的Json串
                    if (modelInfo.Key == model.Name)
                    {
                        for (int i = 0; i < modelInfo.Value.Count; i++)
                        {
                            ProcessKeyValue(sb, modelInfo.Value[i]);
                        }
                    }
                    ///如果是细表,则构造细表的Json串,细表可能存在多行
                    else
                    {
                        if (modelInfo.Value.Count > 0)
                        {
                            ProcessChildModel(sb, modelInfo);
                        }
                    }
                }
                if (sb[sb.Length - 1] == ',')
                    sb.Remove(sb.Length - 1, 1);
                sb.Append("}");
                obj = JObject.Parse(sb.ToString());

            }
            return obj;
        }
        private static void ProcessChildModel(StringBuilder sb, KeyValuePair<string, List<string>> modelInfo)
        {
            sb.Append("\"" + modelInfo.Key + "\":[");
            string firstCellName = modelInfo.Value[0].Split('=')[0].Split('$')[1];
            for (int i = 0; i < modelInfo.Value.Count; i++)
            {
                if (modelInfo.Value[i].Split('=')[0].Split('$')[1] == firstCellName)
                {
                    if (i == 0)
                    {
                        sb.Append("{");
                    }
                    else
                    {
                        ///移除属性后面的逗号
                        sb.Remove(sb.Length - 1, 1);
                        sb.Append("},{");

                    }
                    ProcessKeyValue(sb, modelInfo.Value[i]);
                }
                else
                {
                    ProcessKeyValue(sb, modelInfo.Value[i]);
                }
            }
            sb.Remove(sb.Length - 1, 1).Append("}");
            sb.Append("],");
        }

        //private static void ProcessChildModel(StringBuilder sb, KeyValuePair<string, List<string>> modelInfo)
        //{
        //    sb.Append("\"" + modelInfo.Key + "\":");
        //    List<int> RowList = new List<int>();
        //    for (int i = 0; i < modelInfo.Value.Count; i++)
        //    {
        //        int RowIndex = Convert.ToInt32(modelInfo.Value[i].Split('=')[0].Split('$')[2]);
        //        if (!RowList.Contains(RowIndex))
        //        {
        //            RowList.Add(RowIndex);
        //        }
        //    }
        //    Dictionary<int, List<string>> detailRows = new Dictionary<int, List<string>>();
        //    for (int i = 0; i < RowList.Count; i++)
        //    {
        //        detailRows.Add(RowList[i], new List<string>());
        //    }
        //    for (int i = 0; i < modelInfo.Value.Count; i++)
        //    {
        //        int RowIndex = Convert.ToInt32(modelInfo.Value[i].Split('=')[0].Split('$')[2]);
        //        foreach (KeyValuePair<int, List<string>> detailRow in detailRows)
        //        {
        //            if (detailRow.Key == RowIndex)
        //            {
        //                detailRow.Value.Add(modelInfo.Value[i]);
        //            }
        //        }
        //    }


        //    sb.Append("[");
        //    foreach (KeyValuePair<int, List<string>> detailRow in detailRows)
        //    {
        //        sb.Append("{");
        //        for (int i = 0; i < detailRow.Value.Count; i++)
        //        {
        //            ProcessKeyValue(sb, detailRow.Value[i]);
        //        }
        //        sb.Remove(sb.Length - 1, 1);
        //        sb.Append("},");
        //    }
        //    sb.Remove(sb.Length - 1, 1);
        //    sb.Append("]");

        //}
        /// <summary>
        /// 处理字段名和值
        /// </summary>
        /// <param name="sb"></param>
        /// <param name="decodekev"></param>
        private static void ProcessKeyValue(StringBuilder sb, string decodekev)
        {
            if (decodekev.EndsWith("="))
            {
                sb.Append("\"" + decodekev.Split('=')[0].Split('$')[1] + "\"");
                sb.Append(":");
                sb.Append("\"\"");
            }
            else
            {
                sb.Append("\"" + decodekev.Split('=')[0].Split('$')[1] + "\"");
                sb.Append(":");
                if (decodekev.Split('=')[1] != "on")
                    if (decodekev.Split('=')[1].Contains("\\"))
                    {
                        string s = decodekev.Split('=')[1].Replace("\\", "\\\\");
                        sb.Append("\"" + s + "\"");
                    }
                    else
                    {
                        sb.Append("\"" + decodekev.Split('=')[1] + "\"");
                    }
                else
                    sb.Append("\"true\"");
            }
            sb.Append(",");
        }
        /// <summary>
        /// 将DataTable序列化为Json串
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static string SerializeObject(DataTable dt)
        {
            return JsonConvert.SerializeObject(dt);
        }
        /// <summary>
        /// 将Json反序列化为DataTable
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public static DataTable DeserializeObject(string json)
        {
            return JsonConvert.DeserializeObject<DataTable>(json);
        }
        /// <summary>
        ///功能： 把json 字符串转化成 DataModel 对象
        /// </summary>
        /// <param name="jsonStr">json 字符串</param>
        /// <param name="model">数据模型</param>
        public static void ConvertJsonToDataModel(string jsonStr, DataModel model)
        {
            JObject o = ProcessToJsonObject(jsonStr, model);
            DataModel modelRow = model.NewRow();

            foreach (DataModelColumn column in model.Columns)
            {
                modelRow[column.Name].Value = o[column.Name];
            }
            model.Rows.Add(modelRow);
            #region 明细赋值
            for (int i = 0; i < model.Childs.Count; i++)
            {
                JArray detailRows = (JArray)o[model.Childs[i].Name];
                if (detailRows != null)
                {
                    for (int j = 0; j < detailRows.Count; j++)
                    {
                        DataModel detailRow = model.Childs[i].NewRow();

                        foreach (DataModelColumn detailColumn in model.Childs[i].Columns)
                        {
                            detailRow[detailColumn.Name].Value = detailRows[j][detailColumn.Name];
                        }
                        model.Childs[i].Rows.Add(detailRow);
                    }
                }
            }
            #endregion
            #region 兄弟赋值
            for (int i = 0; i < model.Brothers.Count; i++)
            {
                JArray detailRows = (JArray)o[model.Brothers[i].Name];
                if (detailRows != null)
                {
                    for (int j = 0; j < detailRows.Count; j++)
                    {
                        DataModel detailRow = model.Brothers[i].NewRow();

                        foreach (DataModelColumn detailColumn in model.Brothers[i].Columns)
                        {
                            detailRow[detailColumn.Name].Value = detailRows[j][detailColumn.Name];
                        }
                        model.Brothers[i].Rows.Add(detailRow);
                    }
                }
            }
            #endregion

        }
    }
}
